import re
from django_redis import get_redis_connection
from rest_framework import serializers
from rest_framework_jwt.utils import jwt_encode_handler
from .models import *


class UserSeializers(serializers.ModelSerializer):
    sms_code = serializers.IntegerField(write_only=True)

    class Meta:
        model = User
        fields = ['id', 'username', 'password', 'mobile', 'avatar', 'sms_code']
        extra_kwargs = {
            'username': {'max_length': 20, 'min_length': 2},
            'password': {'max_length': 20, 'min_length': 6, 'write_only': True},
        }

    def validate_username(self, value):
        try:
            User.objects.get(username=value)
        except User.DoesNotExist:
            return value
        raise serializers.ValidationError("用户名已存在")

    def validate_mobile(self, value):
        # # 1 判断手机号是否重复
        # count = User.objects.filter(mobile=mobile).count()
        # if count:
        #     return Response({'success': 0, 'message': '手机号已注册'})
        if not re.match(r'^1[3-9]\d{9}$', value):
            raise serializers.ValidationError("手机号格式错误")
        return value

    def validate(self, attrs):
        conn = get_redis_connection('verify_code')
        mobile = attrs.get('mobile')
        code = conn.get("sms_%s" % mobile)
        if not code:
            raise serializers.ValidationError("验证码失效")
        code = code.decode()
        conn.delete("sms_%s" % mobile)
        if code != str(attrs.get('sms_code')):
            raise serializers.ValidationError("验证码错误")
        attrs.pop('sms_code')
        return attrs







